package com.example.recyclerview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

/**
 * @author W凯
 * @data 2022/9/28
 * @fuction 实体类
 */

public class ItemAdapt  extends RecyclerView.Adapter<ItemAdapt.ViewHolder>{
    private List<itemdata> nmitemdata;//数据源
    private Context myContext;
    private OnItemClickListener myClickListener;
    public   View mview;

    public   boolean status = false;
    //ItemAdapt的构造方法，加入了数据源参数，在构造的时候赋值给nmitemdata
    public ItemAdapt(List<itemdata> mitemdata) {
        nmitemdata = mitemdata;
    }
    //静态内部类， 每个条目对应的布局
    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView names;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            names = (TextView) itemView.findViewById(R.id.textView2);
        }
    }
    //用于创建ViewHolder实例,并把加载的布局传入到ViewHolder的构造函数去
    @NonNull
    @Override
    public ItemAdapt.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }
    //是用于对子项的数据进行赋值,会在每个子项被滚动到屏幕内时执行。position得到当前项的实例
    @Override
    public void onBindViewHolder(@NonNull ItemAdapt.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        itemdata Itemata = nmitemdata.get(position);
        holder.names.setText(Itemata.getName());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(View v) {

                if(status){
                    mview.setBackgroundResource(R.color.white);
                    Log.e("TAG","运行中");
                }
                v.setBackgroundColor(R.color.purple_200);
                mview = v;
                status = true;

                Toast.makeText(MainActivity.getInstance(), "" + holder.names.getText()+"  "+position, Toast.LENGTH_SHORT).show();
            }
        });
//        holder.itemView.setOnClickListener(v -> {
////                Toast.makeText(myContext, "" + position, Toast.LENGTH_SHORT).show();
//            myClickListener.OnClick(position);
//        });
    }
    //返回RecyclerView的子项数目
    @Override
    public int getItemCount() {
        return nmitemdata.size();
    }
    public void setOnItemClickListener(OnItemClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    interface OnItemClickListener{
        void OnClick(int position);
    }


}
